<template>
  <el-dialog
    :title="`日期格式转换`"
    v-model="drawerVisible"
    :draggable="true"
    :overflow="true"
    :close-on-click-modal="false"
    :close-on-press-escape="false"
    top="30px"
    width="900px"
    :destroy-on-close="true"
  >
    <el-form label-position="top">
      <div class="detail-form">
        <!-- 当前时间显示 -->
        <group-title title="当前时间"></group-title>
        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item label="当前时间戳（毫秒）">
              <el-input readonly v-model="currentTime.timestamp" style="width: 100%">
                <template #append>
                  <el-button @click="copyToClipboard(currentTime.timestamp)" size="small">复制</el-button>
                </template>
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="当前时间戳（秒）">
              <el-input readonly v-model="currentTime.timestampSeconds" style="width: 100%">
                <template #append>
                  <el-button @click="copyToClipboard(currentTime.timestampSeconds)" size="small">复制</el-button>
                </template>
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="ISO 8601 格式">
              <el-input readonly v-model="currentTime.iso" style="width: 100%">
                <template #append>
                  <el-button @click="copyToClipboard(currentTime.iso)" size="small">复制</el-button>
                </template>
              </el-input>
            </el-form-item>
          </el-col>
        </el-row>

        <!-- 时间戳转日期 -->
        <group-title title="时间戳转日期"></group-title>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="输入时间戳">
              <el-input
                v-model="timestampToDate.input"
                placeholder="请输入时间戳（支持秒、毫秒）"
                style="width: 100%"
                @input="convertTimestampToDate"
              >
                <template #prepend>
                  <el-select
                    v-model="timestampToDate.unit"
                    placeholder="单位"
                    style="width: 80px"
                    @change="convertTimestampToDate"
                  >
                    <el-option label="毫秒" value="ms" />
                    <el-option label="秒" value="s" />
                  </el-select>
                </template>
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="转换结果">
              <el-input readonly v-model="timestampToDate.result" style="width: 100%">
                <template #append>
                  <el-button @click="copyToClipboard(timestampToDate.result)" size="small">复制</el-button>
                </template>
              </el-input>
            </el-form-item>
          </el-col>
        </el-row>

        <!-- 日期转时间戳 -->
        <group-title title="日期转时间戳"></group-title>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="选择日期时间">
              <el-date-picker
                v-model="dateToTimestamp.input"
                type="datetime"
                placeholder="选择日期时间"
                style="width: 100%"
                @change="convertDateToTimestamp"
              />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="毫秒时间戳">
              <el-input readonly v-model="dateToTimestamp.milliseconds" style="width: 100%">
                <template #append>
                  <el-button @click="copyToClipboard(dateToTimestamp.milliseconds)" size="small">复制</el-button>
                </template>
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="秒时间戳">
              <el-input readonly v-model="dateToTimestamp.seconds" style="width: 100%">
                <template #append>
                  <el-button @click="copyToClipboard(dateToTimestamp.seconds)" size="small">复制</el-button>
                </template>
              </el-input>
            </el-form-item>
          </el-col>
        </el-row>

        <!-- 日期格式转换 -->
        <group-title title="日期格式转换"></group-title>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="输入日期">
              <el-input
                v-model="formatConverter.input"
                placeholder="请输入日期（支持多种格式）"
                style="width: 100%"
                @input="convertDateFormat"
              />
              <div class="format-hint">支持格式：2024-01-01、2024/01/01、2024-01-01 12:00:00、Jan 1, 2024 等</div>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="格式化结果">
              <div class="format-results">
                <div class="format-item" v-for="(format, key) in formatConverter.results" :key="key">
                  <span class="format-label">{{ getFormatLabel(key) }}：</span>
                  <el-input readonly :value="format" size="small">
                    <template #append>
                      <el-button @click="copyToClipboard(format)" size="small">复制</el-button>
                    </template>
                  </el-input>
                </div>
              </div>
            </el-form-item>
          </el-col>
        </el-row>

        <!-- 相对时间计算 -->
        <group-title title="相对时间计算"></group-title>
        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item label="起始日期">
              <el-date-picker
                v-model="relativeTime.startDate"
                type="datetime"
                placeholder="选择起始日期"
                style="width: 100%"
                @change="calculateRelativeTime"
              />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="结束日期">
              <el-date-picker
                v-model="relativeTime.endDate"
                type="datetime"
                placeholder="选择结束日期"
                style="width: 100%"
                @change="calculateRelativeTime"
              />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="时间差">
              <el-input readonly v-model="relativeTime.difference" style="width: 100%">
                <template #append>
                  <el-button @click="copyToClipboard(relativeTime.difference)" size="small">复制</el-button>
                </template>
              </el-input>
            </el-form-item>
          </el-col>
        </el-row>
      </div>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="drawerVisible = false">关闭</el-button>
        <el-button type="primary" @click="refreshCurrentTime">刷新当前时间</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup lang="ts" name="DateConverter">
import { reactive, ref, onMounted, onUnmounted } from "vue";
import { ElMessage } from "element-plus";
import groupTitle from "@/components/application/form/group-title.vue";

interface DrawerProps {}

const drawerVisible = ref(false);
const drawerProps = ref<DrawerProps>({});
let timer: NodeJS.Timeout | null = null;

// 当前时间
const currentTime = reactive({
  timestamp: "",
  timestampSeconds: "",
  iso: ""
});

// 时间戳转日期
const timestampToDate = reactive({
  input: "",
  unit: "ms",
  result: ""
});

// 日期转时间戳
const dateToTimestamp = reactive({
  input: new Date(),
  milliseconds: "",
  seconds: ""
});

// 日期格式转换
const formatConverter = reactive({
  input: "",
  results: {
    yyyy_mm_dd: "",
    yyyy_mm_dd_hh_mm_ss: "",
    mm_dd_yyyy: "",
    dd_mm_yyyy: "",
    iso: "",
    utc: "",
    locale: "",
    relative: ""
  }
});

// 相对时间计算
const relativeTime = reactive({
  startDate: new Date(),
  endDate: new Date(),
  difference: ""
});

// 更新当前时间
const updateCurrentTime = () => {
  const now = new Date();
  currentTime.timestamp = now.getTime().toString();
  currentTime.timestampSeconds = Math.floor(now.getTime() / 1000).toString();
  currentTime.iso = now.toISOString();
};

// 刷新当前时间
const refreshCurrentTime = () => {
  updateCurrentTime();
  ElMessage.success("当前时间已刷新");
};

// 时间戳转日期
const convertTimestampToDate = () => {
  if (!timestampToDate.input) {
    timestampToDate.result = "";
    return;
  }

  try {
    let timestamp = parseInt(timestampToDate.input);
    if (timestampToDate.unit === "s") {
      timestamp = timestamp * 1000;
    }

    const date = new Date(timestamp);
    if (isNaN(date.getTime())) {
      timestampToDate.result = "无效的时间戳";
    } else {
      timestampToDate.result = date.toLocaleString("zh-CN", {
        year: "numeric",
        month: "2-digit",
        day: "2-digit",
        hour: "2-digit",
        minute: "2-digit",
        second: "2-digit"
      });
    }
  } catch (error) {
    timestampToDate.result = "转换失败";
  }
};

// 日期转时间戳
const convertDateToTimestamp = () => {
  if (!dateToTimestamp.input) return;

  const timestamp = new Date(dateToTimestamp.input).getTime();
  dateToTimestamp.milliseconds = timestamp.toString();
  dateToTimestamp.seconds = Math.floor(timestamp / 1000).toString();
};

// 日期格式转换
const convertDateFormat = () => {
  if (!formatConverter.input) {
    Object.keys(formatConverter.results).forEach(key => {
      formatConverter.results[key] = "";
    });
    return;
  }

  try {
    const date = new Date(formatConverter.input);
    if (isNaN(date.getTime())) {
      Object.keys(formatConverter.results).forEach(key => {
        formatConverter.results[key] = "无效日期";
      });
      return;
    }

    formatConverter.results.yyyy_mm_dd = formatDate(date, "YYYY-MM-DD");
    formatConverter.results.yyyy_mm_dd_hh_mm_ss = formatDate(date, "YYYY-MM-DD HH:mm:ss");
    formatConverter.results.mm_dd_yyyy = formatDate(date, "MM/DD/YYYY");
    formatConverter.results.dd_mm_yyyy = formatDate(date, "DD/MM/YYYY");
    formatConverter.results.iso = date.toISOString();
    formatConverter.results.utc = date.toUTCString();
    formatConverter.results.locale = date.toLocaleString("zh-CN");
    formatConverter.results.relative = getRelativeTime(date);
  } catch (error) {
    Object.keys(formatConverter.results).forEach(key => {
      formatConverter.results[key] = "转换失败";
    });
  }
};

// 计算相对时间
const calculateRelativeTime = () => {
  if (!relativeTime.startDate || !relativeTime.endDate) return;

  const start = new Date(relativeTime.startDate).getTime();
  const end = new Date(relativeTime.endDate).getTime();
  const diff = Math.abs(end - start);

  const days = Math.floor(diff / (1000 * 60 * 60 * 24));
  const hours = Math.floor((diff % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
  const minutes = Math.floor((diff % (1000 * 60 * 60)) / (1000 * 60));
  const seconds = Math.floor((diff % (1000 * 60)) / 1000);

  relativeTime.difference = `${days}天 ${hours}小时 ${minutes}分钟 ${seconds}秒`;
};

// 日期格式化函数
const formatDate = (date: Date, format: string): string => {
  const year = date.getFullYear();
  const month = String(date.getMonth() + 1).padStart(2, "0");
  const day = String(date.getDate()).padStart(2, "0");
  const hours = String(date.getHours()).padStart(2, "0");
  const minutes = String(date.getMinutes()).padStart(2, "0");
  const seconds = String(date.getSeconds()).padStart(2, "0");

  return format
    .replace("YYYY", year.toString())
    .replace("MM", month)
    .replace("DD", day)
    .replace("HH", hours)
    .replace("mm", minutes)
    .replace("ss", seconds);
};

// 获取相对时间
const getRelativeTime = (date: Date): string => {
  const now = new Date();
  const diff = now.getTime() - date.getTime();
  const absDiff = Math.abs(diff);

  if (absDiff < 60000) {
    return "刚刚";
  } else if (absDiff < 3600000) {
    const minutes = Math.floor(absDiff / 60000);
    return diff > 0 ? `${minutes}分钟前` : `${minutes}分钟后`;
  } else if (absDiff < 86400000) {
    const hours = Math.floor(absDiff / 3600000);
    return diff > 0 ? `${hours}小时前` : `${hours}小时后`;
  } else {
    const days = Math.floor(absDiff / 86400000);
    return diff > 0 ? `${days}天前` : `${days}天后`;
  }
};

// 获取格式标签
const getFormatLabel = (key: string): string => {
  const labels = {
    yyyy_mm_dd: "YYYY-MM-DD",
    yyyy_mm_dd_hh_mm_ss: "YYYY-MM-DD HH:mm:ss",
    mm_dd_yyyy: "MM/DD/YYYY",
    dd_mm_yyyy: "DD/MM/YYYY",
    iso: "ISO 8601",
    utc: "UTC",
    locale: "本地格式",
    relative: "相对时间"
  };
  return labels[key] || key;
};

// 复制到剪贴板
const copyToClipboard = async (text: string) => {
  try {
    await navigator.clipboard.writeText(text);
    ElMessage.success("已复制到剪贴板");
  } catch (error) {
    ElMessage.error("复制失败");
  }
};

// 接收父组件传过来的参数
const acceptParams = async (params: DrawerProps) => {
  drawerProps.value = params;
  drawerVisible.value = true;
  updateCurrentTime();

  // 启动定时器，每秒更新当前时间
  timer = setInterval(updateCurrentTime, 1000);

  // 初始化日期转时间戳
  convertDateToTimestamp();
  calculateRelativeTime();
};

// 组件挂载时初始化
onMounted(() => {
  updateCurrentTime();
});

// 组件卸载时清理定时器
onUnmounted(() => {
  if (timer) {
    clearInterval(timer);
  }
});

defineExpose({
  acceptParams
});
</script>

<style lang="scss" scoped>
.detail-form {
  flex: 1 1 200px;
  overflow-y: auto;
}
.format-hint {
  margin-top: 4px;
  font-size: 12px;
  color: var(--el-color-info);
}
.format-results {
  .format-item {
    display: flex;
    align-items: center;
    margin-bottom: 8px;
    .format-label {
      display: inline-block;
      flex-shrink: 0;
      width: 140px;
      font-size: 13px;
      color: var(--el-text-color-regular);
    }
    .el-input {
      flex: 1;
    }
  }
}
.dialog-footer {
  display: flex;
  gap: 12px;
  justify-content: flex-end;
}
</style>
